package com.uduemc.biso.node.web.api.controller;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.core.entities.SSystem;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.dto.RequestSCategory;
import com.uduemc.biso.node.web.api.pojo.ResponseSCategories;
import com.uduemc.biso.node.web.api.service.CategoryService;
import com.uduemc.biso.node.web.api.service.SystemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/category")
@Api(tags = "系统分类管理模块")
public class CategoryController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SystemService systemServiceImpl;

    @Resource
    private CategoryService categoryServiceImpl;

    @Resource
    private RequestHolder requestHolder;

    @ApiOperation(value = "系统分类信息", notes = "通过传入的参数 systemId 来获取该系统的所有分类数据信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "systemId", value = "系统 ID", required = true)})
    @PostMapping("/infos-by-system-id")
    public JsonResult getInfosBySystemId(@RequestParam long systemId)
            throws IOException {
        SSystem infoById = systemServiceImpl.getInfoById(systemId);
        if (infoById == null || infoById.getHostId().longValue() != requestHolder.getHost().getId().longValue()
                || infoById.getSiteId().longValue() != requestHolder.getCurrentSite().getId().longValue()) {
            logger.info("systemId: " + systemId);
            JsonResult.illegal();
        }
        // 通过 systemId 获取对应的分类数据
        List<SCategories> currentInfosBySystemId = categoryServiceImpl.getCurrentInfosBySystemId(systemId);
        return JsonResult.ok(currentInfosBySystemId);
    }

    @ApiOperation(value = "提取父级ID对应的系统分类信息", notes = "通过传入的参数 systemId 来获取该系统的所有分类数据信息，适用于后台")
    @ApiImplicitParams({@ApiImplicitParam(name = "systemId", value = "系统 ID", required = true)})
    @PostMapping("/table-data-infos-by-system-id")
    public JsonResult getTableDataInfosBySystemId(@RequestParam long systemId)
            throws IOException {
        SSystem infoById = systemServiceImpl.getInfoById(systemId);
        if (infoById == null || infoById.getHostId().longValue() != requestHolder.getHost().getId().longValue()
                || infoById.getSiteId().longValue() != requestHolder.getCurrentSite().getId().longValue()) {
            logger.info("systemId: " + systemId);
            JsonResult.illegal();
        }
        // 通过 systemId 获取对应的分类数据
        ResponseSCategories responseSCategories = categoryServiceImpl.getCurrentResponseSCategoriesBySystemId(systemId);
        return JsonResult.ok(responseSCategories);
    }

    @ApiOperation(value = "保存单个系统分类数据", notes = "通过传入Json数据，保存系统分类数据")
    @PostMapping("/save")
    public JsonResult save(@Valid @RequestBody RequestSCategory requestSCategoriy, BindingResult errors)
            throws IOException {
        if (errors.hasErrors()) {
            for (FieldError fieldError : errors.getFieldErrors()) {
                String defaultMessage = fieldError.getDefaultMessage();
                String field = fieldError.getField();
                logger.info("field: " + field + "defaultMessage: " + defaultMessage);
                return JsonResult.messageError(field + " " + defaultMessage);
            }
        }

        SCategories sCategories = requestSCategoriy.getSCategories(requestHolder);
        if (sCategories == null) {
            return JsonResult.illegal();
        }

        SCategories data = null;
        if (sCategories.getId() != null && sCategories.getId().longValue() > 0) {
            // 修改
            data = categoryServiceImpl.updateSCategories(sCategories);
        } else {
            // 添加
            data = categoryServiceImpl.insertAppendOrderNum(sCategories);
        }
        if (data == null) {
            return JsonResult.assistance();
        }
        return JsonResult.messageSuccess(data);
    }

    @ApiOperation(value = "保存多条系统分类数据", notes = "通过传入数组的 Json 数据，保存系统分类数据")
    @PostMapping("/save/list")
    public JsonResult saveList(@Valid @RequestBody List<SCategories> listSCategories, BindingResult errors)
            throws IOException {
        if (errors.hasErrors()) {
            for (FieldError fieldError : errors.getFieldErrors()) {
                String defaultMessage = fieldError.getDefaultMessage();
                String field = fieldError.getField();
                logger.info("field: " + field + "defaultMessage: " + defaultMessage);
                return JsonResult.messageError(field + " " + defaultMessage);
            }
        }
        if (CollectionUtils.isEmpty(listSCategories)) {
            return JsonResult.illegal();
        }
        for (SCategories sCategories : listSCategories) {
            if (sCategories.getHostId().longValue() != requestHolder.getHost().getId().longValue()) {
                return JsonResult.illegal();
            }
            if (sCategories.getSiteId().longValue() != requestHolder.getCurrentSite().getId().longValue()) {
                return JsonResult.illegal();
            }
        }

        List<SCategories> updateSPageById = categoryServiceImpl.updateSCategories(listSCategories);
        if (updateSPageById.size() == listSCategories.size()) {
            return JsonResult.messageSuccess("操作成功");
        }
        return JsonResult.assistance();
    }

    /**
     * 修改系统分类的排序，Url中带有 categoryId 为了日志中体现操作的分类
     *
     * @param listSCategories
     * @param categoryId
     * @param errors
     * @return
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws JsonProcessingException
     * @throws IOException
     */
    @ApiOperation(value = "修改系统分类的排序", notes = "通过传入数组的 Json 数据，保存系统分类数据")
    @PostMapping("/update-order/{categoryId:\\d+}")
    public JsonResult updateOrder(@Valid @RequestBody List<SCategories> listSCategories,
                                  @PathVariable("categoryId") long categoryId, BindingResult errors)
            throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
        if (errors.hasErrors()) {
            for (FieldError fieldError : errors.getFieldErrors()) {
                String defaultMessage = fieldError.getDefaultMessage();
                String field = fieldError.getField();
                logger.info("field: " + field + "defaultMessage: " + defaultMessage);
                return JsonResult.messageError(field + " " + defaultMessage);
            }
        }
        if (CollectionUtils.isEmpty(listSCategories)) {
            return JsonResult.illegal();
        }
        for (SCategories sCategories : listSCategories) {
            if (sCategories.getHostId().longValue() != requestHolder.getHost().getId().longValue()) {
                return JsonResult.illegal();
            }
            if (sCategories.getSiteId().longValue() != requestHolder.getCurrentSite().getId().longValue()) {
                return JsonResult.illegal();
            }
        }

        List<SCategories> updateSPageById = categoryServiceImpl.updateSCategories(listSCategories);
        if (updateSPageById.size() == listSCategories.size()) {
            return JsonResult.messageSuccess("操作成功");
        }
        return JsonResult.assistance();
    }

    @ApiOperation(value = "删除系统分类数据", notes = "如果该系统分类下有子分类，一并删除")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "系统分类 ID", required = true)})
    @PostMapping("/delete-its-subclasses")
    public JsonResult delete(@RequestParam("id") long id)
            throws IOException {
        SCategories sCategories = categoryServiceImpl.findOne(id);
        if (sCategories == null || sCategories.getHostId().longValue() != requestHolder.getHost().getId().longValue()
                || sCategories.getSiteId().longValue() != requestHolder.getCurrentSite().getId().longValue()) {
            return JsonResult.illegal();
        }
        // 获取要删除的所有数据
        List<SCategories> listSCategories = categoryServiceImpl.findByAncestors(id);
        if (CollectionUtils.isEmpty(listSCategories)) {
            return JsonResult.assistance();
        }
        boolean delete = categoryServiceImpl.deleteItsSubclasses(id);
        if (!delete) {
            return JsonResult.assistance();
        }
        return JsonResult.messageSuccess("删除成功", listSCategories);
    }
}
